<?php
declare (strict_types = 1);

namespace app\controller;

use app\common\model\Article;
use app\common\model\ArticleCate;
use app\common\model\Content;
use app\common\model\Mod;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;
use Curl\Curl;

class AdminArticle extends AdminInit
{
    public function __construct()
    {
        parent::__construct();
        $cate = ArticleCate::where(1)->select();
        $cate = unlimitforlevel($cate);
        View::assign("cate",$cate);
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $models = Mod::select()->toArray();
        View::assign("models",$models);

        $keyword = request()->param("keyword");
        $model_id = request()->param("model_id");
        $search_field = request()->param("search_field");
        if($keyword && $search_field){
            if ($search_field == 'id'){
                $where[] = ["{$search_field}",'=',"{$keyword}"];
            }else{
                $where[] = ["{$search_field}",'like',"%{$keyword}%"];
            }
        }

        $model_id = request()->param("model_id",0);
        if($model_id != 0){
            $where["model_id"] = $model_id;
        }
        $cate_id = input("param.cate_id",0);
        if($cate_id != 0){
            $where["cate_id"] = $cate_id;
        }
        if(!isset($where)){
            $where = 1;
        }

        $order = Request::param("order",0);
        switch ($order){

            case 'id_asc':
                $o = "id ASC";
                break;
            case 'id_desc':
                $o = "id DESC";
                break;
            case 'hit_asc':
                $o = "rel_hits ASC";
                break;
            case 'hit_desc':
                $o = "rel_hits DESC";
                break;
            case 'oid_asc':
                $o = "ordid asc";
                break;
            case 'oid_desc':
                $o = "ordid desc";
                break;
            case 'status_asc':
                $o = "status asc";
                break;
            case 'status_desc':
                $o = "status desc";
                break;

            default:
                $o = "top DESC,recommend DESC,id DESC";
                break;
        }

        View::assign("order",$order);


        $list = Content::with(["cate","mod"])
            ->where($where)
            ->order($o)
            ->paginate(["query"=>request()->param()]);
        //echo Article::getlastsql();die;
        View::assign("list",$list);
        View::assign("title","文章列表");
        return  view();
    }

    //多选删除
    public function del_all()
    {
        $ids = input("param.ids");
        $res = Content::where("id","in",$ids)->delete();
        if($res){
            return json(["code"=>200,"msg"=>"删除成功"]);
        }else{
            return json(["code"=>4000,"msg"=>"失败"]);
        }

    }

//    修改置顶状态
    public function change_top()
    {
        $id = request()->param("id");
        $res = Content::find($id);
        $arr=[];
        if($res->top ==1){
            $res->top = 0;
            $arr["msg"] = "已取消置顶";
        }else{
            $res->top = 1;
            $arr["msg"] = "已置顶";
        }
        $t = $res->save();
        if($t){
            $arr["code"] = 200;
        }else{
            $arr["code"] = 400;
        }
        return json($arr);
    }
    //change_recommend 修改推荐状态
    public function change_recommend()
    {
        $id = request()->param("id");
        $res = Content::find($id);
        $arr=[];
        if($res->recommend ==1){
            $res->recommend = 0;
            $arr["msg"] = "已取消";
        }else{
            $res->recommend = 1;
            $arr["msg"] = "已推荐";
        }
        $t = $res->save();
        if($t){
            $arr["code"] = 200;
        }else{
            $arr["code"] = 400;
        }
        return json($arr);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        View::assign("title","文章发布");
        return \view();
    }

    //将选中项推送给百度进行收录
    public function push_to_baidu_all()
    {
        $d = request()->param();
        if(config("baiduzhanzhang.autopushststus") == 1){
            if(config("baiduzhanzhang.url")){
                $url = [];
                foreach ($d["ids"] as $v){
                    $t = request()->domain().(string)url('Article/read',["id"=>$v]);

                    array_push($url,$t);
                }
                $push_res = push_to_baidu($url);
                $push_res = json_decode($push_res,true);
                if(isset($push_res["success"])){
                    $msg="成功,并且推送成功，今日剩余推送".$push_res["remain"]."条";
                }else{
                    $msg="成功,推送接口错误，请手动推送";
                }
            }else{
                $msg="成功,未设置自动推送URL，不自动推送";
            }
        }else{
            $msg="成功,未开启自动推送";
        }
        return json(["code"=>200,"msg"=>$msg]);
    }

    //更新网站sitemap
    public function sitemap()
    {
        $ids = Db::name("article")->field("id,last_time")->order("id DESC")->select()->toArray();
        //$ids = array_column($ids["id"]);
        $url = [];

        $xml = '<?xml version="1.0" encoding="utf-8"?>'.PHP_EOL;
        $xml .= '<urlset>'.PHP_EOL;
        foreach ($ids as $v){
            $t = request()->domain().(string)url('Article/read',["id"=>$v["id"]]);
            array_push($url,$t);
            $xml .= "<url>
                <loc>{$t}</loc>
                <lastmod>".date("Y-m-d H:i:s",$v['last_time'])."</lastmod>
                <changefreq>daily</changefreq>
                <priority>0.8</priority>
            </url>".PHP_EOL;

        }
        $xml .='</urlset>'.PHP_EOL;
        file_put_contents("./sitemap.xml",$xml);
        
        $push_res = push_to_baidu($url);
        $push_res = json_decode($push_res,true);
        if(isset($push_res["success"])){
            $msg="成功,并且推送成功，今日剩余推送".$push_res["remain"]."条";
        }else{
            $msg="成功,推送接口错误，请手动推送";
        }
        return json(["code"=>200,"msg"=>$msg]);
    }



    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
       
        $user = $this->user;
        if(!$user){
            return redirect((string) url('index/index',['redirect' => 'index/user/index']));
        }
        $mod = new \app\common\model\ArticleCate();
        $d = $request->post();
        $d["status"] = 1;
        $d["uid"] = $user["id"];
        $d["author"] = $user["nickname"];
        $d["userinfo"] = json_encode($user);
        if(!$d["name"]){
            return  json(["code"=>4000,"msg"=>"name不能为空"]);
        }

        if(isset($d["id"])){
            $res = Db::name("article_cate")->strict(false)->where("id",$d["id"])->update($d);
        }else{
            $res = $mod->save($d);
        }

        if($res){
            return  json(["code"=>200,"msg"=>"成功"]);
        }else{
            return  json(["code"=>4000,"msg"=>"请稍后再试"]);
        }
    }

  

    

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $res = ArticleCate::find($id);
        View::assign("res",$res);
        return view('create');
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源 文章删除
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $id = input("param.id");

        //主库记录删除 软删除
        $res1 = Content::find($id);
        $contentid = $res1->id;
        $res1->delete();

        //文章删除
        if($res1["model_id"] == 1){
            $res2 = Article::where("contentid",$contentid)->find();
            $res2->delete();
        }

        //以下内容后续补充
        //文档删除只有content表 无需过多操作

        //专题删除

        //视频删除

        //图片删除

        if($res1){
            return  json(["code"=>200,"msg"=>"成功"]);
        }else{
            return  json(["code"=>4000,"msg"=>"请稍后再试"]);
        }

    }

    //手动将文章同步到百家号
    public function sync_baijiahao()
    {
        $id = input("param.id");

        $res1 = Content::with(["article"])->where("id",$id)->find()->toArray();
        $url = "https://baijiahao.baidu.com/builderinner/open/resource/article/publish";
        $data["app_id"] = config('web.app_id');
        $data["app_token"] = config('web.app_token');
        $data["title"] =$res1["title"];
        $data["cover_images"][]  =[
            "src"=>'https://micuer.com/'.$res1["prefimg"]
        ];
        $data["origin_url"]  = "https://micuer.com/new/{$res1['id']}.html";
        $data["is_original"]  = 1;
        $data["content"] = "<p>".$res1["article"]["info"]."</p>";
        //$data = json_encode($data);
        $data["cover_images"] = json_encode($data["cover_images"]);

        $data = json_encode($data,JSON_UNESCAPED_UNICODE);

        $curl = new Curl();
        $curl->post($url, $data);
        if ($curl->error) {
            return  json(["code"=>200,"msg"=>$curl->errorMessage]);
        } else {
            if($curl->response->errno == 0){
                //修改文章状态
                $update["baijiahao"] = 1;
                $update["id"] = $id;

                Content::update($update);
                return  json(["code"=>200,"msg"=>$curl->response->errmsg]);
            }else{
                return  json(["code"=>400,"msg"=>$curl->response->errmsg]);
            }

        }
        die;
        if($res1){

        }else{
            return  json(["code"=>4000,"msg"=>"请稍后再试"]);
        }
    }

    public function importWord()
    {
        return \view();
    }

    public function change_pid($id)
    {
        if(\request()->isAjax()){
            $data = \request()->post();
            $res = Content::where("id",$data["id"])->save(["pid"=>$data["pid"]]);
            if($res){
                return  json(["code"=>200,"msg"=>"成功"]);
            }else{
                return  json(["code"=>4000,"msg"=>"请稍后再试"]);
            }
        }
        $content = Content::find($id);
        View::assign("res",$content);
        return \view();
    }


}
